<template>
  <view class="page-container">
    <!-- 导航栏 -->
    <wd-navbar title="审批管理" safeAreaInsetTop placeholder fixed class="z-1">
      <template #left>
        <wd-icon name="thin-arrow-left" @click="handleNavigateback()" />
      </template>
      <template #right>
        <wd-drop-menu>
          <wd-drop-menu-item title="筛选" ref="dropMenuRef" @opened="handleOpened" custom-class="filter-wrapper">
            <wd-form ref="formRef" :model="filterParams" class="form-wrapper">
              <wd-cell title="审批类型" border vertical custom-title-class="filter-item-title">
                <wd-radio-group v-model="filterParams.type" shape="button">
                  <wd-radio v-for="item of typeList" :key="item.value" :value="item.value">{{ item.label }}</wd-radio>
                </wd-radio-group>
              </wd-cell>
              <wd-cell title="审批标题查询" border vertical custom-title-class="filter-item-title">
                <wd-input v-model="filterParams.title" placeholder="请输入审批标题" />
              </wd-cell>
              <wd-cell title="业务员" border vertical custom-title-class="filter-item-title">
                <wd-checkbox-group v-model="filterParams.names" shape="button">
                  <wd-checkbox v-for="item of staffList" :key="item.id" :modelValue="item.id">
                    {{ item.name }}
                  </wd-checkbox>
                  <wd-button class="m-2" @click="handleStaffMore">更多</wd-button>
                </wd-checkbox-group>
              </wd-cell>
              <wd-cell title="提交时间" border vertical custom-title-class="filter-item-title">
                <wd-calendar
                  type="daterange"
                  v-model="filterParams.time"
                  :formatter="formatter"
                  allow-same-day
                  :shortcuts="shortcuts"
                  :on-shortcuts-click="onShortcutsClick"
                  placeholder="请选择日期范围"
                  safe-area-inset-bottom
                />
              </wd-cell>
            </wd-form>
            <view class="submit-wrapper">
              <wd-button plain size="large" class="button-item" @click="handleReset">重置</wd-button>
              <wd-button size="large" class="button-item" @click="handleSubmit">确定</wd-button>
            </view>
          </wd-drop-menu-item>
        </wd-drop-menu>
      </template>
    </wd-navbar>

    <view class="list-wrapper">
      <wd-tabs v-model="activeTab" :sticky="true" auto-line-width @change="handleChangeTab">
        <wd-tab title="未审批" name="1">
          <view>
            <wd-card
              v-for="item of approvalList"
              :key="item.id"
              class="list-card-item"
              @click="handleClickApprovalItem(item)"
            >
              <template #title>
                <view class="flex justify-between items-center">
                  <text class="font-600">{{ item.name }}</text>
                  <text class="approval-status">
                    <text :class="['status-dot', approvalStatusMapCls[item.status]]" />
                    {{ approvalStatusMap[item.status] }}
                  </text>
                </view>
              </template>
              <view class="flex justify-between">
                <view>
                  <p>付款金额：{{ item.amount }}</p>
                  <p>委托方：{{ item.typeName }}</p>
                  <p>收款方：{{ item.typeName }}</p>
                </view>
                <view>
                  <text>{{ item.creator }}</text>
                </view>
              </view>
            </wd-card>

            <wd-loadmore :state="state" @reload="loadmore" />
          </view>
        </wd-tab>
        <wd-tab title="已审批" name="2">
          <view>
            <wd-card
              v-for="item of approvalList"
              :key="item.id"
              class="list-card-item"
              @click="handleClickApprovalItem(item)"
            >
              <template #title>
                <view class="flex justify-between items-center">
                  <text class="font-600">{{ item.name }}</text>
                  <text class="approval-status">
                    <text :class="['status-dot', approvalStatusMapCls[item.status]]" />
                    {{ approvalStatusMap[item.status] }}
                  </text>
                </view>
              </template>
              <view class="flex justify-between">
                <view>
                  <p>付款金额：{{ item.amount }}</p>
                  <p>委托方：{{ item.typeName }}</p>
                  <p>收款方：{{ item.typeName }}</p>
                </view>
                <view class="flex-shrink-0">
                  <text>{{ item.creator }}</text>
                </view>
              </view>
            </wd-card>

            <wd-loadmore :state="state" @reload="loadmore" />
          </view>
        </wd-tab>
      </wd-tabs>
    </view>

    <wd-popup
      v-model="staffPopupVisible"
      position="bottom"
      lock-scroll
      safe-area-inset-bottom
      :hide-when-close="false"
      :duration="100"
      custom-class="staff-popup-wrapper"
    >
      <view>
        <wd-search
          placeholder="输入姓名搜索"
          v-model="keyword"
          hide-cancel
          placeholder-left
          @change="handleSearch"
          @clear="handleClear"
        />
        <view class="staff-list-wrapper">
          <wd-index-bar :sticky="true" v-if="showStaffMoreSortList.length" @vue:mounted="console.log(1111111)">
            <view v-for="item in showStaffMoreSortList" :key="item.index">
              <wd-index-anchor :index="item.index" />
              <wd-checkbox-group v-model="selectStaffList">
                <wd-cell
                  border
                  clickable
                  center
                  v-for="staff in item.data"
                  :key="staff.id"
                  :title="staff.name"
                  :label="staff.dept + '/' + staff.role"
                  title-width="80%"
                  @click="handleClickStaffItem(item.index, staff)"
                >
                  <wd-checkbox :model-value="staff.id" @click.stop="noop" />
                </wd-cell>
              </wd-checkbox-group>
            </view>
          </wd-index-bar>
        </view>
        <view class="staff-submit-wrapper">
          <wd-button plain size="large" class="button-item" @click="handleResetStaff">取消</wd-button>
          <wd-button size="large" class="button-item" @click="handleSubmitStaff">确定</wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { pinyin } from 'pinyin-pro';
import { groupBy, map, orderBy, toPairs } from 'lodash-es';
import { dayjs } from 'wot-design-uni';

// TODO: mock 数据
const mockList = ref([
  { id: 1, name: '广州1', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 22, name: '广州22', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 223, name: '广州223', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 222, name: '广州222', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 321, name: '广州321', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 432, name: '广州432', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 2314, name: '广州2314', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 654, name: '广州654', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 67, name: '广州67', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 89, name: '广州89', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 99, name: '广州99', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 52, name: '广州52', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 657, name: '广州657', status: '1', type: '委托方审批', typeName: '佛山市xxxx', creator: '赵小刚' },
  { id: 11, name: '广州11', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 12, name: '广州12', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 13, name: '广州13', status: '3', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 14, name: '广州14', status: '3', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 15, name: '广州15', status: '3', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 16, name: '广州16', status: '3', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 17, name: '广州17', status: '3', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 18, name: '广州18', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 19, name: '广州19', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 10, name: '广州10', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 111, name: '广州111', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 121, name: '广州121', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 1111, name: '广州1111', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 11111, name: '广州11111', status: '2', type: '服务商审批', typeName: '佛山市yyyy', creator: '赵二刚' },
  { id: 111111, name: '广州111111', status: '2', type: '服务商审批', typeName: '佛山市yyyy22323', creator: '赵二刚' },
  { id: 4, name: '广州', status: '1', type: '付货款申请', typeName: '佛山市', amount: '12345.67', creator: '赵二刚' },
]);

// TODO: 假装是API
const getApprovalListApi = async (params: any) => {
  const { page = 1, size = 5, status = '1' } = params;
  const filterArr = mockList.value?.filter((v: any) => (status === '1' ? v.status === '1' : v.status !== '1'));
  const chunkArr = filterArr.slice((page - 1) * size, page * size);

  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('chunkArr', chunkArr, page, size, filterArr.length);
      resolve({ data: chunkArr, total: filterArr.length, page, size });
    }, 100);
  });
};

const activeTab = ref('1');

const handleChangeTab = async (tab: string) => {
  console.log('tab', tab);
  page.value = 1;
  state.value = 'loading';
  approvalList.value = [];
  await nextTick();
  getApprovalList();
};

const page = ref(1);
const size = ref(5);
const total = ref(0);

const getApprovalList = async (params = { page: 1, size: 6, status: activeTab.value }) => {
  console.log(params.status);
  const res: any = await getApprovalListApi(params);
  total.value = res.total;
  page.value = res.page;
  size.value = res.size;
  if (res.data.length) {
    approvalList.value = [...approvalList.value, ...res.data];
  } else {
    if (total.value === approvalList.value.length) {
      state.value = 'finished';
    }
  }
};

const init = async () => {
  getApprovalList();
};

const approvalList = ref<any[]>([]);
// const noApprovalList = computed(() => mockList.value?.filter((v: any) => v.status === '1'));
// const hadApprovalList = computed(() => mockList.value?.filter((v: any) => v.status === '2' || v.status === '3'));

const state = ref<any>('loading');

const loadmore = () => {
  getApprovalList({ page: page.value, size: size.value, status: activeTab.value });
};

onReachBottom(() => {
  console.log('onReachBottom');
  page.value += 1;
  getApprovalList({ page: page.value, size: size.value, status: activeTab.value });
});
onShow(init);

// 筛选
const defaultParams = {
  type: '1',
  title: '',
  names: [],
  time: [],
};
const filterParams = ref({ ...defaultParams });
const handleOpened = () => {
  console.log('handleOpened');
};

const dropMenuRef = ref();

const formRef = ref();
const handleSubmit = () => {
  const [start, end] = filterParams.value?.time;
  const params = {
    ...filterParams.value,
    time: [dayjs(start)?.format('YYYY-MM-DD 00:00:;00'), dayjs(end)?.format('YYYY-MM-DD 23:59:59')]?.filter(Boolean),
  };
  console.log('handleSubmit', params);
  dropMenuRef.value?.close();
};
const handleReset = () => {
  filterParams.value = { ...defaultParams };
  dropMenuRef.value?.close();
};

const typeList = ref([
  { value: '1', label: '全部' },
  { value: '2', label: '委托方审批' },
  { value: '3', label: '服务商审批' },
  { value: '4', label: '付货款申请审批' },
  { value: '5', label: '付费用申请审批' },
]);

const staffList = ref([
  { name: '张三', id: 11, dept: '业务一部', role: '跟单员' },
  { name: '张四', id: 22, dept: '业务一部', role: '跟单员' },
]);
const staffMoreList = ref([
  { id: 1, name: '啊钟', dept: '业务一部', role: '跟单员' },
  { id: 2, name: '毕夜', dept: '业务二部', role: '跟单员' },
  { id: 3, name: '钟生', dept: '财务部', role: '财务经理' },
  { id: 4, name: '菜狗', dept: '业务一部', role: '跟单员' },
  { id: 5, name: '太生', dept: '销售部', role: '销售经理' },
  { id: 15, name: '柳生', dept: '业务三部', role: '跟单员' },
  { id: 25, name: '刘生', dept: '业务四部', role: '跟单员' },
  { id: 35, name: '来生', dept: '业务五部', role: '跟单员' },
  { id: 45, name: '高生', dept: '总经办', role: '总经理助理' },
  { id: 55, name: '时生', dept: '财务部', role: '财务专员' },
  { id: 6, name: 'Candy', dept: '业务一部', role: '跟单员' },
  { id: 8, name: '@测试', dept: '技术部', role: '技术经理' },
  { id: 7, name: '2123', dept: '业务一部', role: '业务经理' },
  { id: 17, name: '#测试', dept: '技术部', role: '测试开发' },
]);

const staffMoreSortList = ref<any[]>([]);
const groupAndSortList = (arr: any[]) => {
  const indexArr = arr.map((v) => {
    return {
      ...v,
      index: pinyin(v.name?.[0] ?? '', { pattern: 'first' })?.toLocaleUpperCase(),
    };
  });
  const groupObj = groupBy(indexArr, (item) => (/^[A-Za-z]$/.test(item.index) ? item.index : '#'));
  const groupArr = map(toPairs(groupObj), ([index, data]) => ({ index, data }));
  const orderArr = orderBy(groupArr, [(item) => item.index !== '#', 'index'], ['desc', 'asc']);
  return orderArr;
};

const staffPopupVisible = ref(false);
const handleStaffMore = async () => {
  staffPopupVisible.value = true;
  await nextTick();
  setTimeout(() => {
    staffMoreSortList.value = groupAndSortList([...staffList.value, ...staffMoreList.value]);
    showStaffMoreSortList.value = staffMoreSortList.value;
    console.log(showStaffMoreSortList.value);
  }, 300);
};

const selectStaffList = ref<any[]>([]);
const handleResetStaff = () => {
  selectStaffList.value = [];
  staffPopupVisible.value = false;
};
const handleSubmitStaff = () => {
  console.log(selectStaffList.value);
  staffPopupVisible.value = false;
  // filterParams.value.names = [...selectStaffList.value];
};

const showStaffMoreSortList = ref<any[]>([]);

const keyword = ref('');
const handleSearch = () => {
  if (keyword.value) {
    showStaffMoreSortList.value = staffMoreSortList.value?.filter((item) => {
      return item.data?.some((it: any) => {
        return it.name?.includes(keyword.value);
        // || it.dept?.includes(keyword.value)
        // || it.role?.includes(keyword.value);
      });
    });
  } else {
    showStaffMoreSortList.value = staffMoreSortList.value;
  }
};
const handleClear = () => {
  keyword.value = '';
  handleSearch();
};

const handleClickStaffItem = (index: string, item: any) => {
  console.log(index, item, selectStaffList.value);
  if (selectStaffList.value?.includes(item.id)) {
    selectStaffList.value = selectStaffList.value.filter((v) => v !== item.id);
  } else {
    selectStaffList.value.push(item.id);
  }
};
const noop = () => {};

const handleClickApprovalItem = (item: any) => {
  console.log('item', item);
  uni.navigateTo({
    url: `/pages/work/approval/detail?id=${item.id}`,
  });
};

const handleNavigateback = () => {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({
      url: '/pages/index/index',
    });
  }
};

// 设置
const formatter = (day: any) => {
  const date = new Date(day.date);
  const now = new Date();
  const year = date.getFullYear();
  const month = date.getMonth();
  const da = date.getDate();
  const nowYear = now.getFullYear();
  const nowMonth = now.getMonth();
  const nowDa = now.getDate();

  if (year === nowYear && month === nowMonth && da === nowDa) {
    day.topInfo = '今天';
  }
  if (day.type === 'start') {
    day.bottomInfo = '开始';
  }
  if (day.type === 'end') {
    day.bottomInfo = '结束';
  }
  if (day.type === 'same') {
    day.bottomInfo = '开始/结束';
  }
  return day;
};
const shortcuts = ref<Record<string, any>[]>([
  { text: '近7天', day: 7 },
  { text: '近15天', day: 15 },
  { text: '近30天', day: 30 },
]);
const onShortcutsClick = ({ item }: any) => {
  const dayDiff = item.day;
  const endDate = Date.now();
  const startDate = endDate - (dayDiff - 1) * 24 * 60 * 60 * 1000;
  return [startDate, endDate];
};

const approvalStatusMap: any = {
  1: '待审批',
  2: '审批退回',
  3: '审批通过',
};
const approvalStatusMapCls: any = {
  1: 'approval-wait',
  2: 'approval-back',
  3: 'approval-pass',
};
</script>

<style lang="scss" scoped>
.page-container {
  .list-wrapper {
    padding-top: 44px;
    .list-card-item {
      padding-bottom: 10px;
      margin: 8px 10px;
      box-shadow: 0 1px 5px 2px var(--bg-gray-dark);
      .approval-status {
        display: flex;
        flex-shrink: 0;
        align-items: center;
        .status-dot {
          display: inline-block;
          width: 7px;
          height: 7px;
          margin-right: 2px;
          background-color: var(--primary-color);
          border-radius: 50%;
          &.approval-wait {
            background-color: var(--primary-color);
          }
          &.approval-back {
            background-color: var(--danger-color);
          }
          &.approval-pass {
            background-color: var(--success-color);
          }
        }
      }
    }
  }

  .form-wrapper {
    max-height: calc(100vh - var(--window-top) - 200px);
    max-height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom) - 200px);
    max-height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom) - 200px);
    padding: 50px 0 0;
    overflow: auto;
    :deep(.filter-item-title) {
      font-weight: 600;
    }
  }
  .submit-wrapper {
    display: flex;
    gap: 10px;
    justify-content: space-evenly;
    padding: 10px 20px;
    .button-item {
      width: 100%;
    }
  }
  .filter-wrapper {
    :deep(.wd-popup) {
      max-height: 100% !important;
    }
  }
}

.staff-popup-wrapper {
  height: 90vh;
  .staff-list-wrapper {
    height: calc(90vh - var(--window-top) - 150px);
    height: calc(90vh - var(--window-top) - constant(safe-area-inset-bottom) - 150px);
    height: calc(90vh - var(--window-top) - env(safe-area-inset-bottom) - 150px);
    overflow: auto;
  }
  .staff-submit-wrapper {
    display: flex;
    gap: 10px;
    justify-content: space-evenly;
    padding: 10px 20px;
    .button-item {
      width: 100%;
    }
  }
}
</style>
